package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.PhoneUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.constant.GlobalConstant;
import com.hmdp.entity.dto.LoginFormDTO;
import com.hmdp.entity.dto.Result;
import com.hmdp.entity.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.format.DateTimeFormatters;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    UserMapper userMapper;
    @Override
    public Result sendCode(String phone) {
        if(!PhoneUtil.isPhone(phone))
        {
            return Result.fail(GlobalConstant.PHONE_FORMAT_ERROR);
        }
        String code = RandomUtil.randomString(GlobalConstant.CODE_LENGTH);
        String encryptionPhone = DigestUtils.md5DigestAsHex(phone.getBytes());
        redisTemplate.opsForValue().set(encryptionPhone,code,GlobalConstant.CODE_TTL, TimeUnit.MINUTES);
        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
        System.out.println("code:"+code);
        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
        return  Result.ok(code);
    }

    @Override
    public Result login(LoginFormDTO loginForm) {
        if(!PhoneUtil.isPhone(loginForm.getPhone()))
        {
            return Result.fail(GlobalConstant.PHONE_FORMAT_ERROR);
        }
        LambdaQueryWrapper<User> lqw=new LambdaQueryWrapper<>();
        lqw.eq(User::getPhone,loginForm.getPhone());
        User user = userMapper.selectOne(lqw);
        String code = (String)redisTemplate.opsForValue().get(DigestUtils.md5DigestAsHex(loginForm.getPhone().getBytes()));
        if(!code.equals(loginForm.getCode()))
        {
            return Result.fail(GlobalConstant.CODE_ERROR);
        }
        if(user==null)
        {
            user=new User();
            user.setPhone(loginForm.getPhone());
            String suffix = RandomUtil.randomString(GlobalConstant.INIT_USER_NAME_LENGTH);
            user.setNickName(GlobalConstant.USER_PREFIX+suffix);
            userMapper.insert(user);
        }
        String token = UUID.randomUUID().toString();
        String userJson = JSON.toJSONString(user);
        redisTemplate.opsForValue().set(GlobalConstant.TOKE_PREFIX+token,userJson,GlobalConstant.TOKEN_TTL,TimeUnit.MINUTES);
        return Result.ok(token);
    }

    @Override
    public Result me() {
        UserDTO user = UserHolder.getUser();
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        return Result.ok(userDTO);
    }

    @Override
    public Result sign() {
        UserDTO user = UserHolder.getUser();
        LocalDate now = LocalDate.now();
        String format = now.format(DateTimeFormatter.ofPattern("yyyy/MM"));
        String key=GlobalConstant.BITMAP_USER_SIGN_PREFIX+user.getId()+":"+format;
        int day = now.getDayOfMonth()-1;
        redisTemplate.opsForValue().setBit(key,day,true);
        return Result.ok();
    }

    @Override
    public Result signCount() {
        UserDTO user = UserHolder.getUser();
        LocalDate now = LocalDate.now();
        String format = now.format(DateTimeFormatter.ofPattern("yyyy/MM"));
        String key=GlobalConstant.BITMAP_USER_SIGN_PREFIX+user.getId()+":"+format;
        int day = now.getDayOfMonth()-1;
        List<Long> list = redisTemplate.opsForValue().bitField(key,
                BitFieldSubCommands.create()
                        .get(BitFieldSubCommands
                                .BitFieldType
                                .unsigned(day + 1)).valueAt(0));
        if(list==null||list.isEmpty())
        {
            return Result.ok(0);
        }
        Long num=list.get(0);
        Integer count=0;
        while((num&1)!=0)
        {
            count++;
            num>>>=1;
        }
        return Result.ok(count);
    }


}
